import {
  Controller,
  Body,
  Post,
  UseGuards,
  Get,
  Request,
} from '@nestjs/common';
import { ApiResponse, ApiUseTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { AuthService, LoginPayload, RegisterPayload } from './';
import { UsersService } from './../user';
import { ApiResult } from '../config/index';

@Controller('api/auth')
@ApiUseTags('鉴权登陆')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UsersService,
  ) {}
  @Post('login')
  async login(@Body() payload: LoginPayload): Promise<ApiResult> {
    const user = await this.authService.validateUser(payload);
    return ApiResult.SUCCESS(await this.authService.createToken(user));
  }

  @Post('register')
  async register(@Body() payload: RegisterPayload): Promise<ApiResult> {
    const user = await this.userService.create(payload);
    return ApiResult.SUCCESS(await this.authService.createToken(user));
  }

  @ApiBearerAuth()
  @UseGuards(AuthGuard())
  @Get('me')
  async getLoggedInUser(@Request() request): Promise<ApiResult> {
    const el = request;
    return ApiResult.SUCCESS(request.user);
  }

  @Get('metest')
  async test(@Request() request): Promise<ApiResult> {
    return ApiResult.SUCCESS(request.user);
  }
}
